import boto3
import json


def create_sqs():
    # Get the service resource
    sqs = boto3.resource('sqs')

    # Create the queue. This returns an SQS.Queue instance
    queue = sqs.create_queue(QueueName='test', Attributes={'DelaySeconds': '5'})

    # You can now access identifiers and attributes
    print(queue.url)
    print(queue.attributes.get('DelaySeconds'))


def send_message():
    # Create SQS client
    sqs = boto3.client('sqs')
    queue_url = 'https://sqs.us-east-2.amazonaws.com/599885534814/pt-spider-serverless-CoreProductsBestSellers-queue'

    # Send message to SQS queue
    response = sqs.send_message(
        QueueUrl=queue_url,
        # DelaySeconds=10,
        MessageAttributes={
            'Title': {
                'DataType': 'String',
                'StringValue': 'The Whistler'
            },
            'Author': {
                'DataType': 'String',
                'StringValue': 'John Grisham'
            },
            'WeeksOn': {
                'DataType': 'Number',
                'StringValue': '6'
            }
        },
        MessageBody=(
            'Information about current NY Times fiction bestseller for '
            'week of 12/11/2016.'
        )
    )
    print(response['MessageId'])


def send_message2():
    # Get the service resource
    sqs = boto3.resource('sqs')

    # Get the queue
    queue = sqs.get_queue_by_name(QueueName='test')

    # # Create a new message
    response = queue.send_message(MessageBody='boto3', MessageAttributes={
        'Title': {
            'DataType': 'String',
            'StringValue': 'The Whistler'
        },
        'Author': {
            'StringValue': 'Judy',
            'DataType': 'String'
        }
    })

    # The response is NOT a resource, but gives you a message ID and MD5
    print(response.get('MessageId'))
    print(response.get('MD5OfMessageBody'))


def receive_message2():
    # Get the service resource
    sqs = boto3.resource('sqs')

    # Get the queue
    queue = sqs.get_queue_by_name(QueueName='test')

    # Process messages by printing out body and optional author name
    for message in queue.receive_messages(MessageAttributeNames=['Author']):
        # Get the custom author message attribute if it was set
        author_text = ''
        if message.message_attributes is not None:
            author_name = message.message_attributes.get('Author').get('StringValue')
            if author_name:
                author_text = ' ({0})'.format(author_name)

        # Print out the body and author (if set)
        print('Hello, {0}!{1}'.format(message.body, author_text))

        # Let the queue know that the message is processed
        message.delete()


def receive_message3():
    # Get the service resource
    sqs = boto3.resource('sqs')

    # Get the queue

    queue = sqs.get_queue_by_name(QueueName='pt-spider-serverless-CoreProductsBestSellers-queue')
    # queue = sqs.get_queue_by_name(QueueName='pt-spider-serverless-CoreProductsBestSellers-queue')

    # Process messages by printing out body and optional author name
    for message in queue.receive_messages():
        # Get the custom author message attribute if it was set
        if message.message_attributes is not None:
            author_name = message.message_attributes.get('Author').get('StringValue')
            if author_name:
                author_text = ' ({0})'.format(author_name)

        if message.body is not None:
            batch_id = json.loads(message.body)['batchId']

        # Print out the body and author (if set)
        print('batch id, {0}'.format(batch_id))

        sqs_client = boto3.client('sqs')
        response = sqs_client.get_queue_attributes(QueueUrl=queue.url,
                                                   AttributeNames=['ApproximateNumberOfMessages',
                                                                   'ApproximateNumberOfMessagesDelayed'])
        if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            approximate_number_of_messages = response.get("Attributes", dict()).get("ApproximateNumberOfMessages", None)
            approximate_number_of_messages_delayed = response.get("Attributes", dict()) \
                .get("ApproximateNumberOfMessagesDelayed", None)

            print("The attribute approximate_number_of_messages: {}.".format(approximate_number_of_messages))
            print("The attribute approximate_number_of_messages_delayed: {}.".format(
                approximate_number_of_messages_delayed))


        # Let the queue know that the message is processed

        # message.delete()


def receive_message():
    # Create SQS client
    sqs = boto3.client('sqs')

    test_url = 'https://sqs.us-east-2.amazonaws.com/599885534814/coreSpiderMonitor'
    queue_url = 'https://sqs.us-east-2.amazonaws.com/599885534814/pt-spider-serverless-CoreProductsBestSellers-queue'
    queue_monitor_url = 'https://sqs.us-east-2.amazonaws.com/599885534814/pt-spider-serverless-CoreProductsBestSellers-monitor-queue'

    # Receive message from SQS queue
    response = sqs.receive_message(
        QueueUrl=test_url
    )

    message = response['Messages'][0]
    receipt_handle = message['ReceiptHandle']

    if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        approximate_number_of_messages = response.get("Attributes", dict()).get("ApproximateNumberOfMessages", None)
        approximate_number_of_messages_delayed = response.get("Attributes", dict()) \
            .get("ApproximateNumberOfMessagesDelayed", None)

        print("The attribute approximate_number_of_messages: {}.".format(approximate_number_of_messages))
        print(
            "The attribute approximate_number_of_messages_delayed: {}.".format(approximate_number_of_messages_delayed))

    # Delete received message from queue
    # sqs.delete_message(
    #     QueueUrl=queue_url,
    #     ReceiptHandle=receipt_handle
    # )
    print('Received and deleted message: %s' % message)


def processing_message():
    """
    reference
    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/sqs.html
    :return:
    """
    pass


if __name__ == "__main__":
    # create_sqs()
    send_message2()
    # receive_message2()
    # receive_message()
    receive_message3()